﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gueei.Gallery.Core.Repositories;

namespace Gueei.Gallery.Core.Services
{

	public class ReindexService
	{
		private static object _lock = new object();
		private int _totalTags = 0;
		private int _done = 0;
		private bool _working = false;


		private readonly IImageRepository _imageRepo;
		private readonly ITagRepository _tagRepo;

		public ReindexService(IImageRepository imageRepo, ITagRepository tagRepo)
		{
			_imageRepo = imageRepo;
			_tagRepo = tagRepo;
		}

		public int Progress
		{
			get
			{
				lock(_lock)
				{
					if (!_working)
					{
						return 100;
					}					
				}
				if(_totalTags>0)
					return _done * 100/_totalTags;
				return 100;
			}
		}

		public string Message
		{
			get { return "Done " + _done + " tags out of total " + _totalTags; }
		}

		public void StartReindex()
		{
			lock (_lock)
			{
				if (_working) return;
				_working = true;
				_totalTags = _tagRepo.GetTags().Count();
			}
			_done = 0;
			foreach (var t in _tagRepo.GetTags())
			{
				int count = _imageRepo.GetImages().Where(i => i.Tags.Contains(t)).Count();
				t.ItemCount = count;
				_tagRepo.SaveTag(t);
				_done++;
				System.Threading.Thread.Sleep(1000);
			}
			lock (_lock)
			{
				_working = false;
			}
		}
	}
}
